package cn.tedu.sp06.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.protocol.RequestContent;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Filter;

@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器的类型: pre,
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
//位置序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //判断针对当前请求,是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equals(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/dsada?token=dsada
        //获得requst对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)){
            ctx.setSendZuulResponse(false);
            //直接访问响应
            ctx.addZuulResponseHeader("Content-Type","text/html;charset=UTF-8");
            ctx.setResponseBody("Not Login! 未登录");
        }
        //接受token参数
        //如果没有token,阻止继续访问,直接返回响应
        //这个返回值没有任何作用
        return null;
    }
}
